﻿$(function () {
    toastr.options.positionClass = 'toast-bottom-center';
    // 实例
    var vm = new Vue({
        el: '#app',
        data: {
            // 角色与权限
            settingPermission: true, // 等进到本页面就是 true
            settingEditPermission: false,
            settingDisbablePermission: false,
            globalEditPermission:false,
            multiDepartmentPermission: false,


            level: null,
            hospital:null,
            department: null,   // 当前科室
            deviceType: null,    // 当前设备类型
            device: null,
            treeData: [],
            formLabelWidth:'150px',

            formDisabled: true,

            checkInModeOptions: [],// 到诊模式选项

            intervalSpanOptions:[], // 号段长度选项

            setting: {
                id: null,
                level: null,
                appointableCount: null,     // 可预约天数
                earliest: null,             // 可提前签到分钟数
                checkInMode: null,          // 到诊模式  0、自动到站 1、主动到诊
                latestAppoint: null,        // 最迟提前预约分钟数
                unpaidWillBeCancel: null,   // 是否自动取消未付款的预约
                unpaidTimeLimit: null,        // 最晚预约时间
                hisIntervalSpan:1
            },

            defaultProps: {                 // 科室和tree-node对象的映射
                label: 'name',
                children: 'children'
            },

            // 验证规则
            rules: {
                   
            }
        },
        computed: {
            levelName: function () {
                const vm = this;
                var str;
                switch (vm.setting.level) {
                    case 0:
                        str = "Department"
                        break;
                    case 1:
                        str = "DeviceType"
                        break;

                    case 2:
                        str = "Device";
                        break;
                }
                return str;
            },
            autoCancelOptions: function () {
                const vm = this;
                if (vm.level === 0) {
                    return [
                        {
                            label: '开启',
                            value: true
                        },
                        {
                            label: '关闭',
                            value: false
                        },
                        {
                            label: '不设置',
                            value: null
                        }
                    ]
                } else {
                    return [
                        {
                            label: '开启',
                            value: true
                        },
                        {
                            label: '关闭',
                            value: false
                        },
                    ]
                }
            }
        },
        watch: {

        },
        methods: {

            // 自定义表单验证器
            isRequired(rule, value, callback) {
                const vm = this;
                if (vm.level === 0) {
                    if (value === null || value==='') {
                        return callback(new Error('必填'));
                    }
                }
                callback();
            },

            // 获取设置详情
            getDetail() {
                const vm = this;
                abp.ajax({
                    type: 'get',
                    url: `/api/custom-setting/get-setting-detail?level=${vm.level}&depId=${vm.department ? vm.department.id : null}&deviceTypeId=${vm.deviceType ? vm.deviceType.id : null}&deviceId=${vm.device ? vm.device.id : null}`,
                }).then((res) => {
                    if (res.code === 0) {
                        vm.setting = res.data;
                        vm.formDisabled = true;
                    }
                })
               
                
            },

            unpaidWillBeCancelChange(val) {
                const vm = this;
                if (!val) {
                    vm.setting.unpaidWillBeCancel = null;
                }
            },

            checkInModeChange(val) {
                const vm = this;
                if (!val) {
                    vm.setting.checkInMode = null;
                }
            },

            // 编辑  
            setEditable() {
                const vm = this;
                vm.formDisabled = false;
            },

            // 保存 
            save() {
                const vm = this;
                if (vm.level === 0) {
                    vm.setting.departmentId = null;
                }
                vm.$refs.settingForm.validate(valid => {
                    if (valid) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/custom-setting/save`,
                            data: JSON.stringify(vm.setting)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.formDisabled = true;
                            }
                        });
                    }
                })
            },

            // 加载科室（如果是科室用户时）
            loadDepartment() {
                return new Promise(resolve => {
                    if (!vm.multiDepartmentPermission) {
                        // 获取当前登录科室
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-current-user-department"
                        }).then(res => {
                            vm.department = res;
                            resolve();
                        });
                    }
                    else {
                        resolve();
                    }
                });
            },

            // 到诊模式选项加载
            loadCheckInModeOptions() {
                const vm = this;
                abp.ajax({
                    type: "GET",
                    url: "/api/custom-setting/get-check-in-mode"
                }).then(res => {
                    if (res.code === 0) {
                        debugger;
                        vm.checkInModeOptions = res.data;
                    }
                })
            },

            // 加载His号段长度选项
            loadHisIntervalSpanOptions() {
                const vm = this;
                abp.ajax({
                    type: 'get',
                    url: '/api/custom-setting/get-his-interval-span-options'
                }).then(res => {
                    if (res.code === 0) {
                        vm.intervalSpanOptions = res.data;
                    }
                })
            },

            // 加载"科室列表(Admin角色)" 和 当前科室(无admin角色，有DepartmentUser权限)
            loadTreeData() {
                const vm = this;
                return new Promise(resolve => {
                    var url;
                    if (vm.multiDepartmentPermission) { // 如果有管理员角色（multiDepartmentPermission只在admin角色中才有）
                        url = `/api/custom-setting/get-tree-data?depId=`
                    }
                    else {
                        url = `/api/custom-setting/get-tree-data?depId=${vm.department.id}`
                    }
                    abp.ajax({
                        type: "GET",
                        url: url
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.treeData = res.data;
                            vm.level = 0;
                            vm.hospital = res.data[0].name;
                            resolve();
                        }
                    });
                });
            },

            design(id) {
                const vm = this;
                window.open(`/PrintTemplates/design?tempalteId=${id}`);
            },

            // 加载当前权限
            loadPermission() {
                const vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('AppointManagerGroup.CustomSettings')) { // 根权限
                        vm.settingPermission = true;
                        if (abp.auth.isGranted('AppointManagerGroup.CustomSettings.Edit')) { // 编辑权限
                            vm.settingEditPermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.CustomSettings.Disable')) { // 启用/禁用
                            vm.settingDisbablePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.CustomSettings.GlobalEdit')) {
                            vm.globalEditPermission = true;
                        }
                    }
                    if (abp.auth.isGranted('OthersGoup.Others.MuMultiDepartment')) { // 多科室检查项目管理权限
                        vm.multiDepartmentPermission = true;
                    }
                    resolve();
                });
            },

            // 点击树节点
            nodeClicked(node, obj, aa) {
                const vm = this;
                switch (node.level) {
                    case 'hospital':
                        vm.level = 0;
                        vm.hospital = node.name;
                        vm.department = null;
                        vm.deviceType = null;
                        vm.device = null;
                        break;

                    case 'department':
                        vm.level = 1;
                        vm.department = {
                            id: node.id,
                            name: node.name
                        }
                        vm.deviceType = null;
                        vm.device = null;
                        break;

                    case 'deviceType':
                        vm.level = 2; 
                        var depNode = obj.parent.data
                        vm.department = {
                            id: depNode .id,
                            name: depNode.name
                        };
                        vm.deviceType = {
                            id: node.id,
                            name: node.name
                        };
                        vm.device = null;
                        break;

                    case 'device':
                        vm.level = 3;
                        var depNode = obj.parent.parent.data;
                        vm.department = {
                            id: depNode.id,
                            name: depNode.name
                        }
                        var deviceTypeNode = obj.parent.data;
                        vm.deviceType = {
                            id: deviceTypeNode.id,
                            name: deviceTypeNode.name
                        }
                        vm.device = {
                            id: node.id,
                            name: node.name
                        }
                }
                vm.$refs.settingForm.resetFields();
                vm.getDetail();
            },

            // 初始化
            init() {
                const vm = this;
                vm.loadPermission()
                    .then(() => {
                        vm.loadDepartment().then(() => {
                            vm.loadTreeData().then(() => {
                                vm.getDetail();
                                vm.loadCheckInModeOptions();
                                vm.loadHisIntervalSpanOptions();
                            });
                        })
                    });
            }
        },
        created() {
            const vm = this;
            vm.rules = {
                appointableCount: [
                    {
                        validator: vm.isRequired,
                        trigger: ['blur']
                    }
                ],
                autoAppointableCount:[
                    {
                        validator: vm.isRequired,
                        trigger: ['blur']
                    }
                ],
                latestAppoint: [
                    {
                        validator: vm.isRequired,
                        trigger: ['blur']
                    }
                ],
                earliest: [
                    {
                        validator: vm.isRequired,
                        trigger: ['blur']
                    }
                ],
                checkInMode: [
                    {
                        validator: vm.isRequired,
                        trigger: ['blur','change']
                    }
                ],
                unpaidWillBeCancel: [
                    {
                        validator: vm.isRequired,
                        trigger: ['blur','change']
                    }
                ],
                unpaidTimeLimit: [
                    {
                        validator: vm.isRequired,
                        trigger: ['blur']
                    }
                ]
            }
        },
        mounted() {
            const vm = this;
            vm.init();
           
        }
    });
});